package cn.luo.dao;

import cn.luo.entity.Blogs;
import cn.luo.entity.User;
import cn.luo.uilt.SessionUitls;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.index.Index;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository      //放到容器
public class UserDao {
    @Autowired
    MongoTemplate mongoTemplate;   //数据库模板

    //添加用户
    public void addUser(User user){
        Index index = new Index();
        index.on("username", Sort.Direction.ASC);
        System.out.println("添加前的id = " + user.getId());
        mongoTemplate.indexOps("t_user").ensureIndex(index);
        mongoTemplate.save(user);   //如果 id 存在就修改，如果不存在就添加
        System.out.println("添加后的id = " + user.getId());
    }

    //根据用户名查看用户信息
    public User findUserByName(String username){
        Query query = new Query(Criteria.where("username").is(username));
        User user = mongoTemplate.findOne(query,User.class);
        return user;
    }

    //分页查询
    public List<Blogs> findByPage2(int start, int num){
        System.err.println(SessionUitls.getUid());
        Query query = new Query(Criteria.where("uid").is(SessionUitls.getUid()));  //获取用户id
        query.skip(start).limit(num);
        List<Blogs> lst = mongoTemplate.find(query,Blogs.class);
        return lst;
    }

    //计算总页数
    public long total(){
        Query query = new Query(Criteria.where("uid").is(SessionUitls.getUid()));  //获取用户id
        long count = mongoTemplate.count(query, Blogs.class);
        return count;
    }
}